<template>
    <div class="temu-lirun-container layout-padding">
        <div class="mb15">
            <TableSearch :search="state.tableData.search" @search="onSearch" />

            <el-button size="default" type="success" class="ml10" @click="onOpenAddProduct('add')">
                <el-icon>
                    <ele-FolderAdd />
                </el-icon>
                新增TEMU利润核算项目
            </el-button>

            <el-button size="default" type="success" class="ml10" @click="editZuochuanSubsidy()">
                编辑佐川补贴配置
            </el-button>

            <el-button size="default" type="success" class="ml10" @click="editZuochuanDistribution()">
                编辑佐川配送配置
            </el-button>

            <el-button size="default" type="success" class="ml10" @click="editAcrossSubsidy()">
                编辑Across补贴配置
            </el-button>

            <el-button size="default" type="success" class="ml10" @click="editAcrossDistribution()">
                编辑Across配送配置
            </el-button>
        </div>

        <div class="temu-lirun-padding layout-padding-view layout-padding-auto">
            <Table ref="tableRef" v-bind="state.tableData" class="temu-lirun" @pageChange="onTablePageChange"
                @sortHeader="onSortHeader">

                <template v-slot:tableOperate="row">
                    <el-button size="small" text type="primary" @click="writeTemuLirun(row.row)">
                        填写数据
                    </el-button>
                    <el-button size="small" text type="primary" @click="onOpenAddProduct('edit', row.row.id)">
                        编辑
                    </el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="onTableDelRow(row.row)">
                        <template #reference>
                            <el-button size="small" text type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </Table>
        </div>
        <temuLirunProductDialog ref="temuLirunProductDialogRef" @refresh="getTableData()" />
        <ZuochuanSubsidyDialog ref="zuochuanSubsidyDialogRef" />
        <ZuochuanDistributionDialog ref="zuochuanDistributionDialogRef" />
        <AcrossSubsidyDialog ref="acrossSubsidyDialogRef" />
        <AcrossDistributionDialog ref="acrossDistributionDialogRef" />
    </div>
</template>

<script setup lang="ts" name="temu-lirun">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useTemuLirunApi } from '/@/api/calculate/temuLirun';

// 引入 api 请求接口
const temuLirunApi = useTemuLirunApi();

// 引入组件
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const temuLirunProductDialog = defineAsyncComponent(() => import('/@/views/calculate/lirun/temu/component/temuLirunProductDialog.vue'));
const ZuochuanSubsidyDialog = defineAsyncComponent(() => import('/@/views/calculate/lirun/temu/component/ladderDialog.vue'));
const ZuochuanDistributionDialog = defineAsyncComponent(() => import('/@/views/calculate/lirun/temu/component/ladderDialog.vue'));
const AcrossSubsidyDialog = defineAsyncComponent(() => import('/@/views/calculate/lirun/temu/component/ladderDialog.vue'));
const AcrossDistributionDialog = defineAsyncComponent(() => import('/@/views/calculate/lirun/temu/component/ladderDialog.vue'));

const temuLirunProductDialogRef = ref();
const zuochuanSubsidyDialogRef = ref();
const zuochuanDistributionDialogRef = ref();
const acrossSubsidyDialogRef = ref();
const acrossDistributionDialogRef = ref();

// 定义变量内容
const router = useRouter();
const tableRef = ref<RefType>();
const state = reactive<TableDemoState>({
    tableData: {
        // 列表数据（必传）
        data: [],
        // 表头内容（必传，注意格式）
        header: [
            { key: 'name', colWidth: '', title: '项目名称', type: 'text', isCheck: true },
            { key: 'plOne', colWidth: '', title: '一级品类', type: 'text', isCheck: true },
            { key: 'plTwo', colWidth: '', title: '二级品类', type: 'text', isCheck: true },
            { key: 'variantCodeOne', colWidth: '', title: '变体1', type: 'text', isCheck: true },
            { key: 'variantCodeTwo', colWidth: '', title: '变体2', type: 'text', isCheck: true },
            { key: 'status', colWidth: '', title: '状态', type: 'text', isCheck: true },
            { key: 'headFreightPrice', colWidth: '', title: '头程运费价格', type: 'text', isCheck: true },
            { key: 'foreignWarehousePrice', colWidth: '', title: '海外仓价格', type: 'text', isCheck: true },
            { key: 'acrossStoragePrice', colWidth: '', title: 'across保管价格', type: 'text', isCheck: true },
            { key: 'taxPer', colWidth: '', title: '税金比例', type: 'text', isCheck: true },
        ],
        // 配置项（必传）
        config: {
            total: 0, // 列表总数
            loading: true, // loading 加载
            isBorder: false, // 是否显示表格边框
            isSerialNo: true, // 是否显示表格序号
            isSelection: true, // 是否显示表格多选
            isOperate: true, // 是否显示表格操作栏
        },
        // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
        search: [
            { label: '项目名称', prop: 'name', placeholder: '支持模糊搜索', required: false, type: 'input' },
        ],
        // 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
        param: {
            pageNum: 1,
            pageSize: 10,
        },
        // 打印标题
        printName: 'temu利润核算项目',
    },
});

// 打开新增菜单弹窗
const onOpenAddProduct = (type: string, productId?: number) => {
    temuLirunProductDialogRef.value.openDialog(type, productId);
};

// 编辑佐川补贴配置
const editZuochuanSubsidy = ()=>{
    zuochuanSubsidyDialogRef.value.openDialog("temu_lirun_zuochuan_subsidy");
}

// 编辑佐川配送费配置
const editZuochuanDistribution = ()=>{
    zuochuanDistributionDialogRef.value.openDialog("temu_lirun_zuochaun_distribution_price");
}

// 编辑Across补贴配置
const editAcrossSubsidy = ()=>{
    acrossSubsidyDialogRef.value.openDialog("temu_lirun_across_subsidy");
}

// 编辑Across配送费配置
const editAcrossDistribution = ()=>{
    acrossDistributionDialogRef.value.openDialog("temu_lirun_across_distribution_price");
}

//搜索
const onSearch = (data: EmptyObjectType) => {
    state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
    tableRef.value.pageReset();
};

// 初始化列表数据
async function getTableData() {
    state.tableData.config.loading = true;
    const productData = await temuLirunApi.temuLirunProductList(state.tableData.param);
    console.log(productData.data);
    if (productData.data == null)
        return Promise.resolve(true);

    const newProductData: TemuLirunProduct[] = productData.data.rows;
    const showProductData = [];
    if (undefined != newProductData) {
        for (const item of newProductData) {
            var status = '';
            if (item.status == 0) {
                status = '未填写完成';
            } else {
                status = '已核算完成';
            }

            const showProductItem = {
                id: item.id,
                name: item.name,
                plOne: item.plOne,
                plTwo: item.plTwo,
                variantCodeOne: item.variantCodeOne,
                variantCodeTwo: item.variantCodeTwo,
                status: status,
                headFreightPrice: item.headFreightPrice,
                foreignWarehousePrice: item.foreignWarehousePrice,
                acrossStoragePrice: item.acrossStoragePrice,
                taxPer: item.taxPer,
            }
            showProductData.push(showProductItem);
        }
    }

    state.tableData.data = showProductData;
    state.tableData.config.total = productData.data.total;
    setTimeout(() => {
        state.tableData.config.loading = false;
    }, 500);
};

// 删除当前项回调
async function onTableDelRow(row: EmptyObjectType) {
    const deleteItem = {
        id: row.id,
    }
    await temuLirunApi.deleteTemuLirunProduct(deleteItem);

    ElMessage.success(`删除${row.name}成功！`);
    getTableData();
};

//填写数据
const writeTemuLirun = (row: EmptyObjectType) => {
    const params: EmptyObjectType = { id: row.id };
    router.push({
        path: '/calculate/lirun/temu/instance',
        query: params,
    });
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
    state.tableData.param.pageNum = page.pageNum;
    state.tableData.param.pageSize = page.pageSize;
    getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
    state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
    getTableData();
});
</script>

<style scoped lang="scss">
.temu-lirun-container {
    .temu-lirun-padding {
        padding: 15px;

        .temu-lirun {
            flex: 1;
            overflow: hidden;
        }
    }
}
</style>
